<template>
    <div class="engineering-container">
        <!-- 左侧菜单目录 -->
        <cardBox class="leftMenu" title="文档目录" icon="&#xe6f2;"> 
            <div class="table-tips">📝 右键点击目录节点，可通过菜单执行操作</div>
            <div class="menu-tree">
                <treeMenu 
                :treeData="menuList" 
                name="lable" 
                ref="treeMenu" 
                nodeKey="id" 
                isRightMenu 
                :showRoleAdd="permissions.showRoleAdd"
                :showRoleDel="permissions.showRoleDel"
                :showRoleEdit="permissions.showRoleEdit"
                @menuLeftClick="handleMenuClick"
                @addMenuItem="handleAddMenu" 
                @delMenuItem="handleDelTreeMenu" 
                @editMenuItem="handleAddMenu"
                v-if="menuList.length > 0"
            />
            <el-button 
                type="primary" 
                size="small" 
                icon="el-icon-plus" 
                class="add-menu-btn"
                @click="handleAddMenu({node:{}},false,1)" 
                v-if="menuList.length == 0 && permissions.showRoleAdd">
                新增菜单
            </el-button>  
            </div>
        </cardBox>

        <!-- 右侧内容区域 -->
        <cardBox class="right-panel" title="文档管理"> 
            <template #right>
                <div class="search-box">
                    <el-input 
                        v-model="searchName" 
                        placeholder="搜索名称/文件..." 
                        prefix-icon="el-icon-search"
                        size="small"
                        clearable
                        @keyup.enter="getDocFileList"
                    />
                </div>
                <el-button 
                    type="primary" 
                    size="small" 
                    @click="getDocFileList" 
                    icon="el-icon-search"
                    class="add-data-btn"
                >
                    查询
                </el-button>
                <el-tooltip class="item" effect="dark" content="无新增权限" placement="top-start" :disabled="permissions.showRoleAdd == 1">
                    <el-button 
                        type="primary" 
                        size="small" 
                        @click="handleAddData" 
                        icon="el-icon-plus"
                        class="add-data-btn"
                        :disabled="permissions.showRoleAdd == 0"
                    >
                        添加资料
                    </el-button>
                </el-tooltip>
                
            </template>
            <div class="documents-container">
                <div v-if="tableList.length > 0" class="documents-grid">
                    <div 
                        v-for="item in tableList" 
                        :key="item.id" 
                        class="document-card"
                    >
                        <div class="list-header">
                            <div class="file-icon">
                               <i :class="getFileIcon(item.fileName)"></i>
                            </div>
                            <div class="file-info">
                                <h4 class="file-name">{{ item.name }}</h4>
                                <p class="file-desc">{{ item.fileName }}</p>
                            </div>
                            <div class="card-actions show-actions">
                                <el-tooltip content="无编辑权限" placement="top" :disabled="permissions.showRoleEdit == 1">
                                    <el-link
                                        type="primary" 
                                        icon="el-icon-edit" 
                                        @click="handleEditNameData(item)"
                                         class="edit-btn"
                                         :disabled="permissions.showRoleEdit == 0" :underline="false"
                                    >编辑</el-link>
                                </el-tooltip>
                                <el-tooltip content="无删除权限" placement="top" :disabled="permissions.showRoleDel == 1">
                                    <el-link 
                                        type="danger" 
                                        icon="el-icon-delete" 
                                        @click="handleDelData(item)"
                                        class="delete-btn"
                                        :disabled="permissions.showRoleDel == 0" :underline="false" style="margin-left: 10px;"
                                    >删除</el-link>
                                </el-tooltip>
                            </div>
                        </div>
                        <div class="card-footer">
                            <span class="file-size">{{ getFileType(item.fileName) }}</span>
                            <div class="action-btns">
                                <el-button 
                                    size="mini" 
                                    @click="handlePreview(item)"
                                    class="preview-btn"
                                >
                                    预览
                                </el-button>
                                <el-button 
                                    size="mini" 
                                    type="primary" 
                                    @click="downloadCurrentFile(item)"
                                    class="download-btn"
                                >
                                    下载
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
                 <!-- 空状态 -->
                <noData v-if="tableList.length == 0" showData description="当前目录下还没有任何文档，点击'添加资料'上传第一个文档">
                </noData>
            </div>    
        </cardBox>

        <!-- 预览弹窗 -->
        <el-dialog 
            title="文档预览" 
            v-dialogDrag 
            :visible.sync="previewDialogVisible" 
            width="900px" 
            :before-close="handleCancelPreview"
        >
            <div class="preview-content">
                <img :src="url" width="100%"/>
            </div>
        </el-dialog>

        <!-- 侧边抽屉预览 -->
         <el-drawer
            :visible.sync="drawer"
            direction="ltr"
            :size='700'
            :before-close="handleCancelPreview"
            :with-header="false">
            <iframe class="pdfFrame" :src="url" frameborder="0" width="100%" height="98%" ></iframe>
        </el-drawer>

        <!-- 资料名称编辑弹窗 -->
        <el-dialog 
            title="编辑文档名称" 
            v-dialogDrag 
            :visible.sync="nameDialogVisible" 
            width="500px" 
            :before-close="handleCancelData"
            custom-class="edit-dialog"
        >
            <el-form ref="dataForm" :model="dataForm" label-width="80px">
                <el-form-item label="名称">
                    <el-input 
                        size="medium" 
                        prefix-icon="el-icon-edit"
                        v-model="dataForm.name" 
                        placeholder="请输入文档名称"
                        maxlength="50"
                        show-word-limit
                    />
                </el-form-item>
            </el-form>
            <div class="dialog-footer">
                <el-button @click="handleCancelData" size="small" icon="el-icon-circle-close" class="cancel-btn">取消</el-button>
                <el-button type="primary" @click="handleSaveName" size="small" icon="el-icon-circle-check" class="confirm-btn">保存配置</el-button>
            </div>
        </el-dialog>

        <!-- 资料管理弹窗 -->
        <el-dialog 
            title="添加资料" 
            v-dialogDrag 
            :visible.sync="dataDialogVisible" 
            width="500px" 
            :before-close="handleCancelData"
            custom-class="upload-dialog"
        >
            <el-form ref="dataForm" :model="dataForm" label-width="80px">
                <el-form-item label="名称" required>
                    <el-input 
                        size="medium" 
                        prefix-icon="el-icon-edit"
                        v-model="dataForm.name" 
                        placeholder="请输入资料名称"
                        maxlength="50"
                        show-word-limit
                    />
                </el-form-item>
                <el-form-item label="文件" required>
                    <el-upload
                        class="upload-area"
                        action=""
                        :http-request="uploadFile"
                        :on-change="handleUploadChange"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :before-upload="beforeUpload"
                        :auto-upload="false"
                        :file-list="fileList"
                        drag
                        ref="upload"
                    >
                        <div class="upload-content">
                            <i class="el-icon-upload"></i>
                            <div class="upload-text">
                                <p>点击或将文件拖拽到此处</p>
                                <p class="upload-tip">支持单个文件上传,大小不超过150M</p>
                            </div>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div class="dialog-footer">
                <el-button @click="handleCancelData" size="small" icon="el-icon-circle-close" class="cancel-btn">取消</el-button>
                <el-button type="primary" @click="handleSaveData" size="small" icon="el-icon-circle-check" class="confirm-btn">保存配置</el-button>
            </div>
        </el-dialog>

        <!-- 菜单管理弹窗 -->
        <addMenuDialog  :visible.sync="menuDialogVisible" :menuForm="menuform" :parent-name="parentName" @cancelMenu="handleCancelMenu" @saveMenu="handleSaveMenu"/>
    </div>
</template>

<script>
import bus from '@/utils/eventBus.js';
import cardBox from "../../components/base/cardBox.vue";
import treeMenu from '@/components/base/treeMenu.vue'
import {DocFileAdd,DocFileDel,getByTreeID,GetDocTree,DocTreeAdd,DocTreeEdit,DocTreeDel,EditFileName} from '../../api/https'
import noData from '@/components/base/noData.vue';
import addMenuDialog from '@/components/base/addMenuDialog.vue';
import permissionMixin from '@/utils/permission.js'
import { findLeafNodes } from '@/utils/treeUtils';
export default ({
    name:'engineering',
    mixins: [permissionMixin],
    components:{cardBox,treeMenu,noData,addMenuDialog},
    data() {
        return{
            stationId:sessionStorage.getItem("stationId") || '',
            menuList:[],
            searchName:'',
            nodeId:'',
            tableList:[],
            previewDialogVisible:false,
            drawer:false,
            url:'',
            dataForm:{},
            nameDialogVisible:false,
            dataDialogVisible:false,
            fileList:[],
            fd: null,
            editMenu:false,
            treeNodeLevel:'',
            menuform:{},
            menuDialogVisible:false,
            previewFileName:'',
            parentName:''
        }
    },
    created(){
        this.initBasin()
        this.getTreeList()
    },
    activated(){
        this.initBasin()
        const newStationId = sessionStorage.getItem("stationId");
        if (this.stationId !== newStationId) {
            this.stationId = newStationId;
            this.clearData()
            this.getTreeList()
        }
    },
    deactivated(){
       bus.$off('station-changed', this.handleStationChanged);
    },
    beforeDestroy(){
        this.clearData()
        this.$refs.treeMenu = null;
        this.$refs.dataForm = null;
        this.$refs.upload = null;
        if (this.fd) {
            this.fd = null;
        }
    },
    computed: {
        permissions() {
            return this.getPermissions() || {}
        }
    },
    methods:{
        initBasin() {
            bus.$emit('showBasin', true);
            bus.$off('station-changed', this.handleStationChanged);
            bus.$on('station-changed', this.handleStationChanged);
        },
        handleStationChanged(newStationId, targetRoute) {
            if (!targetRoute || targetRoute === this.$route.name) {
                this.stationId = newStationId;
                this.clearData()
                this.getTreeList()
            }
        },
        clearData() {
            this.menuList = [];
            this.tableList = [];
            this.searchName = '';
            this.nodeId = '';
            this.url = '';
            this.dataForm = {};
            this.fileList = [];
            this.fd = null;
        },
        getTreeList(){
            GetDocTree({
                stationid:this.stationId
            }).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0 ){
                    this.menuList = res.data || []

                    const leafInfo = findLeafNodes(this.menuList);
                    this.nodeId = leafInfo.nodeId;

                    this.$nextTick(()=>{
                        this.$refs.treeMenu.$refs.tree.setCurrentKey(this.nodeId);
                        this.getDocFileList()
                    })
                }else{
                    this.menuList = []
                }
            })
        },
        handleMenuClick(data){
            this.nodeId = data.id
            this.getDocFileList()
        },
        getDocFileList(){
            if(this.nodeId != ''){
                getByTreeID({
                    DocTreeID:this.nodeId,
                    fileName:this.searchName
                }).then(res=>{
                    if(res.isSuccess && res.data && res.data.length > 0){
                        this.tableList = res.data || []
                    }else{
                        this.tableList = []
                    }
                })
            }else{
                this.$message.error('请选择目录');
            }
        },
        getFileIcon(fileName) {
            if (!fileName) return 'el-icon-document';
            
            const extension = fileName.split('.').pop().toLowerCase();
            
            const iconMap = {
                // 图片
                'jpg': 'el-icon-picture', 
                'jpeg': 'el-icon-picture', 
                'png': 'el-icon-picture',
                'gif': 'el-icon-picture', 
                'bmp': 'el-icon-picture', 
                'svg': 'el-icon-picture',
                
                // PDF
                'pdf': 'el-icon-document',
                
                // html
                'default': 'el-icon-document'
            };
            
            return iconMap[extension] || iconMap['default'];
        },
        getFileType(fileName){
            if (!fileName) return '文档';
            if(fileName.includes('png') ||fileName.includes('jpg') || fileName.includes('jpeg') || fileName.includes('bmp') || fileName.includes('gif') || fileName.includes('svg')){
                return '图片'
            }else{
                return '文档'
            }

        },
        handlePreview(row){
            const data = row.files[0].url
            if(data.includes('html') || data.includes('pdf')){
                this.drawer = true
                this.url = data
            }else if(data.includes('png') ||data.includes('jpg') || data.includes('jpeg') || data.includes('bmp') || data.includes('gif')){
                this.previewDialogVisible = true
                this.previewFileName = row.name
                this.url = data
            }else{
                this.$message.error('该格式文件暂时无法预览！')
            }
        },
        handleCancelPreview(){
            this.previewDialogVisible = false
            this.drawer = false
            this.url = ''
        },
        downloadCurrentFile(row){
            window.open(row.files[0].url, '_blank');
        },
        handleDelData(data){
            this.$confirm(`确认删除 ${data.name} 的资料及文件？删除后不可恢复，请谨慎操作！`,'提示',{
                type:'warning',
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                confirmButtonClass: 'el-button--danger',
            }).then(() => {
                DocFileDel(data.id).then(res=>{
                    if(res.isSuccess){
                        this.getDocFileList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {}); 
        },
        handleEditNameData(data){
            this.dataForm = {...data}
            this.nameDialogVisible = true
        },
        handleCancelData(){
            this.dataDialogVisible = false
            this.nameDialogVisible = false
            this.fileDialogVisible = false
            this.editData = false
            this.dataForm = {}
            this.fd = null
            this.fileList = []
        },
        handleSaveName(){
            EditFileName({
                id:this.dataForm.id,
                docTreeID:this.nodeId,
                name:this.dataForm.name,
                fileName:this.dataForm.fileName,
                stationId:this.stationId
            }).then(res=>{
                if(res.isSuccess){
                    this.handleCancelData()
                    this.getDocFileList()
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        },
        handleAddData(){
            if(this.nodeId == ''){
                this.$message.error('请先选择要添加资料的菜单！');
                return false
            }else{
                this.dataDialogVisible = true
                this.editData = false
            }
        },
        beforeUpload(file){
            const maxData = file.size / 1024 / 1024 < 150;
            if (!maxData) {
                this.$message.error('上传文件不能超过150MB!');
            }
            return maxData
        },
        uploadFile (file) {
            const fileObj = file.file;
            this.fd.append('files', fileObj)
        },
        handleUploadChange(){
            const fd = new FormData()
            this.fd = fd
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        handleSaveData(){
            if(!this.dataForm.name){
                this.$message.warning('请输入名称！')
                return false
            }

            const uploadFiles = this.$refs.upload.uploadFiles;
            if (uploadFiles.length === 0) {
                this.$message.warning('请先选择要上传的文件！');
                return false;
            }
            this.$refs.upload.submit()
            this.fd.append('DocTreeID',this.nodeId)
            this.fd.append('StationId',this.stationId)
            this.fd.append('Name',this.dataForm.name)
            DocFileAdd(this.fd).then(res=>{
                if(res.isSuccess){
                    this.handleCancelData()
                    this.getDocFileList()
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        },
        handleAddMenu(data,isEdit,treeNodeLevel){
            this.editMenu = isEdit
            this.treeNodeLevel = treeNodeLevel || ''
            if(isEdit){
                const _editData = Object.assign({},data.node)
                this.menuform = {..._editData}
                 this.parentName = ''
            }else{
                if(treeNodeLevel == 2){
                    this.parentName = data.lable
                }else{
                    this.parentName = ''
                }
                this.menuform = {
                    id: 0,
                    treeid:0,
                    stationid: this.stationId,
                    treeName:'',
                    uptreeid: treeNodeLevel == 1 ? data.node.uptreeid || 0 : data.node.treeid || 0,
                }
            }
            this.menuDialogVisible = true
        },
        handleCancelMenu(){
            this.menuDialogVisible = false
            this.menuform = {}
            this.treeNodeLevel = ''
        },
        handleSaveMenu(menuForm) {
            const apiCall = this.editMenu ? DocTreeEdit(menuForm) : DocTreeAdd(menuForm);

            apiCall.then(res => {
                if (res.isSuccess) {
                    this.handleCancelMenu();
                    this.getTreeList();
                    this.$message.success(this.editMenu ? '菜单更新成功' : '菜单添加成功');
                } else {
                    this.$message.error(res.errorMessage);
                }
            }).catch(error => {
                this.$message.error('操作失败，请重试');
            })
        },
        handleDelTreeMenu(data){
            this.$confirm(`确认删除名称为 ${data.lable} 的节点？删除后不可恢复，请谨慎操作！`,'提示',{
                type:'warning',
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                confirmButtonClass: 'el-button--danger',
            }).then(() => {
                DocTreeDel({id:data.node.id}).then(res=>{
                    if(res.isSuccess){
                        this.getTreeList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {}); 
            
        },
    }
})
</script>

<style scoped lang="scss">
.engineering-container {
    display: grid;
    grid-template-columns: 300px 1fr;
    height: calc(100vh - 120px);
    .leftMenu{
       width: 300px;
        height: calc(100vh - 120px);
        flex-shrink: 0;
        .tree-container{
            height: calc(100vh - 200px);
            overflow-y: auto;
        }
    }
    .right-wrapper{
        height: calc(100vh - 120px);
        overflow: auto;
        margin: 0px 0 0 10px;
    }

    // 右侧面板
    .right-panel{
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        margin-left: 10px;

        .search-box {
            margin-right: 10px;
            .el-input {
                width: 280px;

                ::v-deep .el-input__inner {
                    border: 1px solid #e0e6ed;
                    transition: all 0.3s ease;

                    &:focus {
                        border-color: #409eff;
                        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
                    }
                }
            }
        }

        .documents-container {
            flex: 1;
            padding: 24px;
            overflow-y: auto;

            .documents-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
                gap: 20px;
            }

            .document-card {
                background: white;
                border: 1px solid #e8f4fd;
                border-radius: 12px;
                padding: 20px;
                transition: all 0.3s ease;
                cursor: pointer;
                position: relative;
                overflow: hidden;

                &:hover {
                    transform: translateY(-4px);
                    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
                    border-color: #409eff;
                }

                .list-header {
                    display: flex;
                    align-items: flex-start;
                    margin-bottom: 16px;
                    border-bottom: 1px solid #f0f0f0;
                    padding:15px 0;
                    .file-icon {
                        width: 48px;
                        height: 48px;
                        background: linear-gradient(135deg, #409EFF, #66b1ff);
                        border-radius: 6px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        margin-right: 12px;
                        flex-shrink: 0;

                        i {
                            font-size: 20px;
                            color: white;
                        }
                    }

                    .file-info {
                        flex: 1;
                        min-width: 0;

                        .file-name {
                            margin: 0 0 4px 0;
                            font-size: 16px;
                            font-weight: 600;
                            color: #2c3e50;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                        }

                        .file-desc {
                            margin: 0;
                            font-size: 14px;
                            color: #909399;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                        }
                    }

                    .card-actions {
                        opacity: 0;
                        transform: translateX(10px);
                        transition: all 0.3s ease;
                        display: flex;
                        gap: 4px;

                        &.show-actions {
                            opacity: 1;
                            transform: translateX(0);
                        }

                        .el-button {
                            padding: 6px;
                            color: #909399;
                            font-size: 18px;

                            &:hover {
                                color: #409eff;
                                background: #f0f7ff;
                                border-radius: 6px;
                            }
                            &.delete-btn{
                                color: #f56c6c;
                                margin-left: 0px !important;
                            }
                            &.edit-btn{
                                color: #409eff;
                            }

                            &.delete-btn:hover {
                                color: #f56c6c;
                                background: #fef0f0;
                            }
                        }
                    }
                }

                .card-footer {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;

                    .file-size {
                        font-size: 12px;
                        color: #909399;
                        background: #f5f7fa;
                        padding: 4px 8px;
                        border-radius: 4px;
                    }

                    .action-btns {
                        display: flex;
                        gap: 8px;

                        .el-button {
                            border-radius: 6px;
                            padding: 6px 12px;
                            font-size: 12px;

                            &.preview-btn {
                                color: #409eff;
                                border-color: #409eff;

                                &:hover {
                                    background: #f0f7ff;
                                }
                            }

                            &.download-btn {
                                background: linear-gradient(135deg, #409eff, #66b1ff);
                                border: none;

                                &:hover {
                                    background: linear-gradient(135deg, #66b1ff, #409eff);
                                    transform: translateY(-1px);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}


// 上传区域样式
::v-deep .upload-dialog {
    .upload-area {
        .el-upload-dragger {
            width: 100%;
            border: 2px dashed #e0e6ed;
            border-radius: 12px;
            background: #fafbfc;
            transition: all 0.3s ease;

            &:hover {
                border-color: #409eff;
                background: #f0f7ff;
            }

            .upload-content {
                .el-icon-upload {
                    font-size: 48px;
                    color: #c0c4cc;
                    margin-bottom: 16px;
                }

                .upload-text {
                    p {
                        margin: 8px 0;
                        color: #606266;

                        &.upload-tip {
                            font-size: 12px;
                            color: #909399;
                        }
                    }
                }
            }
        }
    }
}

// 抽屉预览样式
.preview-drawer {
    .drawer-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16px 24px;
        background: white;
        border-bottom: 1px solid #e0e6ed;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

        h3 {
            margin: 0;
            color: #2c3e50;
        }
    }
}


.document-card {
    animation: fadeIn 0.5s ease;
}
.table-tips{
    margin: 10px;
}

</style>